/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var rob = function (root) {
  if (!root) return [0, 0]

  function dfs(node) {
    //递归出口
    if (!node) return [0, 0]

    //按照后序遍历的方式遍历二叉树：从叶子节点层层向上计算每个节点的状态，最终得到根节点的状态
    const left = dfs(node.left)
    const right = dfs(node.right)

    //不选择根节点：左、右节点可选可不选
    const noSelect = Math.max(left[0], left[1]) + Math.max(right[0], right[1])
    //选择根节点：左、右节点不能选
    const select = node.val + left[0] + right[0]
    //返回该节点的状态：[不选该节点的最大收益，选择该节点的最大收益]
    return [noSelect, select]
  }

  const res = dfs(root)

  return Math.max(res[0], res[1])
}; 